<template>
	<view>
		<view class="goods_list">

			<view class="goods-item" v-for="(goods, i) in goodsList" :key="i" @click="gotoDetail(goods)">

				<!-- 商品左侧图片区域 -->
				<view class="goods-item-left">
					<image :src="goods.goods_small_logo || defaultPic" class="goods-pic" mode="widthFix"></image>
				</view>

				<!-- 商品右侧信息区域 -->
				<view class="goods-item-right">
					<!-- 商品标题 -->
					<view class="goods-name">
						{{goods.goods_name}}
					</view>
					<view class="goods-info-box">
						<!-- 商品价格 -->
						<view class="goods-price">
							￥{{goods.goods_price|tofixed}}
						</view>
					</view>
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 请求参数对象
				queryObj: {
					// 查询关键词
					query: '',
					// 商品分类ID
					cid: '',
					// 页码值
					pagenum: 1,
					// 每页显示多少条数据
					pagesize: 10
				},
				// 商品列表的数据
				goodsList: [],
				// 商品总数
				total: 0,
				// 当商品没图片时显示
				defaultPic: 'http://image5.suning.cn/uimg/b2c/newcatentries/0000000000-000000000715469339_1_400x400.jpg',
				// 是否正在请求数据
				isLoading: false

			};
		},
		onLoad(options) {
			// 将页面跳转前的参数保存
			this.queryObj.query = options.query || '';
			this.queryObj.cid = options.cid || '';
			// 获取商品列表数据
			this.getGoodsList()
		},
		methods: {
			// 获取商品列表数据
			async getGoodsList(cb) {
				// 打开节流阀
				this.isLoading = true;
				const {
					data: res
				} = await uni.$http.get('/goods/search', this.queryObj)
				// 关闭节流阀
				this.isLoading = false;
				cb && cb();
				if (res.meta.status !== 200) return uni.$showMsg();
				// 将请求数据分开存储
				this.goodsList = [...this.goodsList, ...res.message.goods];
				console.log(res.message);
				this.total = res.message.total;
			},
			gotoDetail(item) {
				uni.navigateTo({
					url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id,
				})
			}
		},
		filters: {
			tofixed(num) {
				return Number(num).toFixed(2)
			}
		},
		// 上拉触底事件
		onReachBottom() {
			// 判断是否还有下一页数据
			if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$showMsg('没有下一页数据了')
			// 判断是否在请求数据
			if (this.isLoading) return
			this.queryObj.pagenum += 1;
			// 重新获取列表数据
			this.getGoodsList()
		},
		// 下拉刷新页面
		onPullDownRefresh() {
			// 重置关键数据
			this.queryObj.pagenum = 1;
			this.total = 0;
			this.isLoading = false;
			this.goodsList = [];
			//重新发起请求
			this.getGoodsList(() => {
				uni.stopPullDownRefresh()
			})
		}
	}
</script>

<style lang="scss">
	.goods-item {
		display: flex;
		padding: 10px 5px;
		border-bottom: 1px solid #e5e5e5;

		.goods-item-left {
			margin-right: 5px;

			.goods-pic {
				width: 100px;
				height: 100px;
				display: block;
			}
		}

		.goods-item-right {
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			.goods-name {
				font-size: 13px;
			}

			.goods-info-box {
				.goods-price {
					font-size: 16px;
					color: #c00000;
				}
			}
		}
	}
</style>
